package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"markedit/internal/model"
	"markedit/internal/service"
)

type ConfigHandler struct {
	configService *service.ConfigService
	logger        *logrus.Logger
}

func NewConfigHandler(configService *service.ConfigService, logger *logrus.Logger) *ConfigHandler {
	return &ConfigHandler{
		configService: configService,
		logger:        logger,
	}
}

// GetConfig 获取配置
// @Summary 获取配置
// @Description 获取应用程序配置
// @Tags Config
// @Produce json
// @Param key query string false "配置键"
// @Success 200 {object} model.APIResponse
// @Router /api/config [get]
func (h *ConfigHandler) GetConfig(c *gin.Context) {
	key := c.Query("key")
	
	if key != "" {
		value := h.configService.Get(key)
		c.JSON(http.StatusOK, model.APIResponse{
			Success: true,
			Data: map[string]interface{}{
				"key":   key,
				"value": value,
			},
			Message: "Configuration retrieved successfully",
		})
	} else {
		config := h.configService.GetAll()
		c.JSON(http.StatusOK, model.APIResponse{
			Success: true,
			Data:    config,
			Message: "All configurations retrieved successfully",
		})
	}
}

// GetAllConfig 获取所有配置
// @Summary 获取所有配置
// @Description 获取所有应用程序配置
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Router /api/config/all [get]
func (h *ConfigHandler) GetAllConfig(c *gin.Context) {
	config := h.configService.GetAllConfig()

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    config,
		Message: "All configurations retrieved successfully",
	})
}

// UpdateConfig 更新配置
// @Summary 更新配置
// @Description 更新应用程序配置
// @Tags Config
// @Accept json
// @Produce json
// @Param config body map[string]interface{} true "配置数据"
// @Success 200 {object} model.APIResponse
// @Failure 400 {object} model.ErrorResponse
// @Router /api/config [put]
func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
	var config map[string]interface{}
	if err := c.ShouldBindJSON(&config); err != nil {
		h.logger.Errorf("Failed to bind request: %v", err)
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Invalid request body",
			Message: err.Error(),
		})
		return
	}

	err := h.configService.Update(config)
	if err != nil {
		h.logger.Errorf("Failed to update config: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to update configuration",
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "Configuration updated successfully",
	})
}

// SetConfig 设置单个配置项
// @Summary 设置单个配置项
// @Description 设置单个配置项的值
// @Tags Config
// @Accept json
// @Produce json
// @Param request body map[string]interface{} true "配置项"
// @Success 200 {object} model.APIResponse
// @Failure 400 {object} model.ErrorResponse
// @Router /api/config/set [post]
func (h *ConfigHandler) SetConfig(c *gin.Context) {
	var request struct {
		Key   string      `json:"key" binding:"required"`
		Value interface{} `json:"value" binding:"required"`
	}

	if err := c.ShouldBindJSON(&request); err != nil {
		h.logger.Errorf("Failed to bind request: %v", err)
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Invalid request body",
			Message: err.Error(),
		})
		return
	}

	err := h.configService.Set(request.Key, request.Value)
	if err != nil {
		h.logger.Errorf("Failed to set config: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to set configuration",
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data: map[string]interface{}{
			"key":   request.Key,
			"value": request.Value,
		},
		Message: "Configuration set successfully",
	})
}

// GetEditorConfig 获取编辑器配置
// @Summary 获取编辑器配置
// @Description 获取编辑器相关配置
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Router /api/config/editor [get]
func (h *ConfigHandler) GetEditorConfig(c *gin.Context) {
	config := h.configService.GetEditorConfig()

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    config,
		Message: "Editor configuration retrieved successfully",
	})
}

// GetRenderConfig 获取渲染配置
// @Summary 获取渲染配置
// @Description 获取渲染相关配置
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Router /api/config/render [get]
func (h *ConfigHandler) GetRenderConfig(c *gin.Context) {
	config := h.configService.GetRenderConfig()

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    config,
		Message: "Render configuration retrieved successfully",
	})
}

// GetExportConfig 获取导出配置
// @Summary 获取导出配置
// @Description 获取导出相关配置
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Router /api/config/export [get]
func (h *ConfigHandler) GetExportConfig(c *gin.Context) {
	config := h.configService.GetExportConfig()

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    config,
		Message: "Export configuration retrieved successfully",
	})
}

// ResetConfig 重置配置
// @Summary 重置配置
// @Description 重置配置为默认值
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/config/reset [post]
func (h *ConfigHandler) ResetConfig(c *gin.Context) {
	err := h.configService.Reset()
	if err != nil {
		h.logger.Errorf("Failed to reset config: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to reset configuration",
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "Configuration reset to defaults successfully",
	})
}

// SaveConfig 保存配置
// @Summary 保存配置
// @Description 保存当前配置到文件
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/config/save [post]
func (h *ConfigHandler) SaveConfig(c *gin.Context) {
	err := h.configService.Save()
	if err != nil {
		h.logger.Errorf("Failed to save config: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to save configuration",
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "Configuration saved successfully",
	})
}

// LoadConfig 加载配置
// @Summary 加载配置
// @Description 从文件加载配置
// @Tags Config
// @Produce json
// @Success 200 {object} model.APIResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/config/load [post]
func (h *ConfigHandler) LoadConfig(c *gin.Context) {
	err := h.configService.Load()
	if err != nil {
		h.logger.Errorf("Failed to load config: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to load configuration",
			Message: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "Configuration loaded successfully",
	})
}